package com.sunday.fangbeibei.activity;

import java.io.File;
import java.io.FileNotFoundException;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.ClipboardManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.reflect.TypeToken;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.sunday.fangbeibei.R;
import com.sunday.fangbeibei.cache.ApplicationCache;
import com.sunday.fangbeibei.constants.ApplicationConstants;
import com.sunday.fangbeibei.http.HttpResponseInterface;
import com.sunday.fangbeibei.http.HttpTool;
import com.sunday.fangbeibei.orm.BaseResult;
import com.sunday.fangbeibei.tool.MethodUtil;
import com.sunday.fangbeibei.widget.ActionSheet;
import com.sunday.fangbeibei.widget.ActionSheet.ActionSheetListener;

/**
 * 个人信息
 * 
 * @author 晨曦
 *
 */
public class UserInfoActivity extends BaseFragmentActivity implements OnClickListener,ActionSheetListener,HttpResponseInterface{
	
	private File image=null;
	
	private String logoPath;
	private int sexValue;
	
	private TextView sex;
	private ImageView logo;
	
	private int type;
	
	
	@Override
	protected void createActivity(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		setContentView(R.layout.user_info_layout);
		loadView();
	}

	
	private void loadView(){
		
		TextView title=(TextView) findViewById(R.id.title);
		ImageView back=(ImageView) findViewById(R.id.back);
		title.setText("个人信息");
		back.setOnClickListener(this);
		
		logo=(ImageView) findViewById(R.id.logo);
		TextView name=(TextView) findViewById(R.id.name);
		sex=(TextView) findViewById(R.id.sex);
		TextView company=(TextView) findViewById(R.id.company);
		final TextView number=(TextView) findViewById(R.id.number);
		TextView mobile=(TextView) findViewById(R.id.mobile);
		
		
		RelativeLayout logorl = (RelativeLayout) findViewById(R.id.logorl);
		RelativeLayout sexrl = (RelativeLayout) findViewById(R.id.sexrl);
		RelativeLayout passwordrl = (RelativeLayout) findViewById(R.id.passwordrl);
		RelativeLayout mobilerl = (RelativeLayout) findViewById(R.id.mobilerl);
		
		DisplayImageOptions option = new DisplayImageOptions.Builder().cacheInMemory(true).cacheOnDisc(true).build();
		ImageLoader.getInstance().displayImage(ApplicationCache.INSTANCE.getUserInfo().getPath(), logo, option);
		
		LinearLayout companyll=(LinearLayout) findViewById(R.id.companyll);
		if(ApplicationCache.INSTANCE.getUserInfo().getType()==3){
			companyll.setVisibility(View.GONE);
			number.setVisibility(View.GONE);
		}
		
		name.setText(ApplicationCache.INSTANCE.getUserInfo().getName());
		String ss="";
		if(ApplicationCache.INSTANCE.getUserInfo().getSex()==1){
			ss="男";
		}else if(ApplicationCache.INSTANCE.getUserInfo().getSex()==2){
			ss="女";
		}else if(ApplicationCache.INSTANCE.getUserInfo().getSex()==3){
			ss="未知";
		}
		sex.setText(ss);
		name.setText(ApplicationCache.INSTANCE.getUserInfo().getName());
		company.setText(ApplicationCache.INSTANCE.getUserInfo().getStoreName());
		mobile.setText(ApplicationCache.INSTANCE.getUserInfo().getMobi());
		number.setText(ApplicationCache.INSTANCE.getUserInfo().getStoreCode());
		
		number.setOnLongClickListener(new OnLongClickListener() {
			
			@Override
			public boolean onLongClick(View v) {
				// TODO Auto-generated method stub
				ClipboardManager cm = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
				cm.setText(number.getText().toString());
				Toast.makeText(mContext, "门店码已粘贴到剪贴板", Toast.LENGTH_SHORT).show();
				return true;
			}
		});
		
		logorl.setOnClickListener(this);
		sexrl.setOnClickListener(this);
		passwordrl.setOnClickListener(this);
		mobilerl.setOnClickListener(this);
	}
	

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch(v.getId()){
		case R.id.back:
			finish();
			break;
		case R.id.logorl:
			type=1;
			setTheme(R.style.ActionSheetStyleIOS7);
			ActionSheet.createBuilder(this, getSupportFragmentManager())
			.setCancelButtonTitle("取消")
			.setOtherButtonTitles("拍照", "从相册选择")
			.setCancelableOnTouchOutside(true).setListener(this).show();
			break;
		case R.id.sexrl:
			type=2;
			setTheme(R.style.ActionSheetStyleIOS7);
			ActionSheet.createBuilder(this, getSupportFragmentManager())
			.setCancelButtonTitle("取消")
			.setOtherButtonTitles("男", "女")
			.setCancelableOnTouchOutside(true).setListener(this).show();
			break;
		case R.id.passwordrl:
			Intent in=new Intent(mContext, ModifyPasswordActivity.class);
			startActivity(in);
			break;
		case R.id.mobilerl:
			Intent in2=new Intent(mContext, ModifyMobileActivity.class);
			startActivity(in2);
			break;
		}
		
	}

	

	@Override
	protected void onActivityResult(int arg0, int arg1, Intent arg2) {
		// TODO Auto-generated method stub
		super.onActivityResult(arg0, arg1, arg2);
		if(arg1==RESULT_OK){
			/*if(arg0==3){

				Uri uri = arg2.getData();   
		        String [] proj={MediaStore.Images.Media.DATA};  
		        Cursor cursor = managedQuery( uri,  
		                proj,                 // Which columns to return  
		                null,       // WHERE clause; which rows to return (all rows)  
		                null,       // WHERE clause selection arguments (none)  
		                null);                 // Order-by clause (ascending by name)  
		          
		        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);  
		        cursor.moveToFirst();  
		          
		        String path = uri.getPath();  
				
		        image=new File(path);
		        
			}*/
			
			if(arg0==2){
				
				Intent intent = new Intent("com.android.camera.action.CROP");
				intent.setDataAndType(Uri.fromFile(image), "image/*");
				intent.putExtra("crop", "true");// crop=true 有这句才能出来最后的裁剪页面.
				intent.putExtra("aspectX", 1);// 这两项为裁剪框的比例.
				intent.putExtra("aspectY", 1);// 
				intent.putExtra("output", Uri.fromFile(image));
				intent.putExtra("outputFormat", "JPEG");// 返回格式
		        startActivityForResult(intent, 3);   
			}else if(arg0==3){
			
				if(image==null){
					return;
				}
				try {
					show("正在上传");
					RequestParams params=new RequestParams();
					params.put("imgFile", image);
					HttpTool.HttpPost(0, mContext, ApplicationConstants.SERVER_URL+"/mobi/pic/upload", params, this, new TypeToken<BaseResult<String>>() {
					}.getType());
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					disMiss();
				}
				
			}else if(arg0==4){
				
				File localImage=new File(MethodUtil.getPath(mContext, arg2.getData()));
				Intent intent = new Intent("com.android.camera.action.CROP");
				intent.setDataAndType(Uri.fromFile(localImage), "image/*");
				intent.putExtra("crop", "true");// crop=true 有这句才能出来最后的裁剪页面.
				intent.putExtra("aspectX", 1);// 这两项为裁剪框的比例.
				intent.putExtra("aspectY", 1);// 
				image=new File(Environment.getExternalStorageDirectory(),"temp.jpg");
				intent.putExtra("output", Uri.fromFile(image));
				intent.putExtra("outputFormat", "JPEG");// 返回格式
		        startActivityForResult(intent, 3);   
		        
			}
		}
	
	}


	
	

	@Override
	public void onDismiss(ActionSheet actionSheet, boolean isCancel) {
		// TODO Auto-generated method stub
		
	}


	@Override
	public void onOtherButtonClick(ActionSheet actionSheet, int index) {
		// TODO Auto-generated method stub
		if(type==1){
			if(index==0){
				Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
				image=new File(Environment.getExternalStorageDirectory(),"temp.jpg");
	            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(image));
	            /*intent.putExtra("crop", "true");
	            // aspectX aspectY 是宽高的比例
	            intent.putExtra("aspectX", 1);
	            intent.putExtra("aspectY", 1);*/
	            startActivityForResult(intent, 2);
			}else if(index==1){
				Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
				intent.addCategory(Intent.CATEGORY_OPENABLE);
				intent.setType("image/*");
		        if(android.os.Build.VERSION.SDK_INT>=android.os.Build.VERSION_CODES.KITKAT){                  
			        startActivityForResult(intent, 4);    
				}else{          
					image=new File(Environment.getExternalStorageDirectory(),"temp.jpg");
		            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(image));
					intent.putExtra("crop", "true");
			        // aspectX aspectY 是宽高的比例
			        intent.putExtra("aspectX", 1);
			        intent.putExtra("aspectY", 1);
			        startActivityForResult(intent, 3);   
				}   
				
			}
		}else if(type==2){
			if(index==0){
				sexValue=1;
				RequestParams params=new RequestParams();
				params.put("userId", ApplicationCache.INSTANCE.getUserInfo().getId());
				params.put("key", "sex");
				params.put("value", 1);
				HttpTool.HttpPost(2, mContext, ApplicationConstants.SERVER_URL+"/mobi/account/updateproperty", params, this, new TypeToken<BaseResult>() {
				}.getType());
			}else if(index==1){
				sexValue=2;
				RequestParams params=new RequestParams();
				params.put("userId", ApplicationCache.INSTANCE.getUserInfo().getId());
				params.put("key", "sex");
				params.put("value", 2);
				HttpTool.HttpPost(2, mContext, ApplicationConstants.SERVER_URL+"/mobi/account/updateproperty", params, this, new TypeToken<BaseResult>() {
				}.getType());
			}
		}
	}


	@Override
	public void onResponse(int requsetCode, boolean resultStatus, Object result) {
		// TODO Auto-generated method stub
		switch(requsetCode){
		case 0:
			BaseResult<String> result1=(BaseResult<String>) result;
			if(resultStatus){
				
				logoPath=result1.getResult();
				RequestParams params=new RequestParams();
				params.put("userId", ApplicationCache.INSTANCE.getUserInfo().getId());
				params.put("key", "path");
				params.put("value", logoPath);
				HttpTool.HttpPost(1, mContext, ApplicationConstants.SERVER_URL+"/mobi/account/updateproperty", params, this, new TypeToken<BaseResult>() {
				}.getType());
				
			}else{
				disMiss();
				Toast.makeText(mContext, "上传头像失败！", Toast.LENGTH_SHORT).show();
			}
			break;
		case 1:
			if(resultStatus){
				disMiss();
				Toast.makeText(mContext, "修改头像成功！", Toast.LENGTH_SHORT).show();
				ApplicationCache.INSTANCE.getUserInfo().setPath(logoPath);
				ImageLoader.getInstance().displayImage(ApplicationCache.INSTANCE.getUserInfo().getPath(), logo);
			}else{
				disMiss();
				Toast.makeText(mContext, "修改头像失败！", Toast.LENGTH_SHORT).show();
			}
			break;
		case 2:
			if(resultStatus){
				Toast.makeText(mContext, "修改性别成功！", Toast.LENGTH_SHORT).show();
				ApplicationCache.INSTANCE.getUserInfo().setSex(sexValue);
				if(ApplicationCache.INSTANCE.getUserInfo().getSex()==1){
					sex.setText("男");
				}else if(ApplicationCache.INSTANCE.getUserInfo().getSex()==2){
					sex.setText("女");
				}
			}else{
				Toast.makeText(mContext, "修改性别失败！", Toast.LENGTH_SHORT).show();
			}
			break;
		}
	}


	@Override
	public void onFailure() {
		// TODO Auto-generated method stub
		disMiss();
	}
	
	
}
